package io.zhengsh.nio.files;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class AsynchronousFileChannelDemo3 {

    public static void main(String[] args) throws IOException, InterruptedException {
        Path path = Paths.get("/Users/zhengsh/" +
                "sourcecode.io/zhengsh-vvip/nio/src/main/resources/01.txt");
        AsynchronousFileChannel fileChannel = null;
        try {

            fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        long position = 0;

        buffer.put("hello! 2022".getBytes(StandardCharsets.UTF_8));
        buffer.flip();

        Future<Integer> write = fileChannel.write(buffer, 0);

        while (!write.isDone()) ;

        System.out.println("写数据完成");

        TimeUnit.SECONDS.sleep(1000);
    }
}
